<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {
	
	function index(){
		$username = $this->input->get_post('username');
		$password = $this->input->get_post('password');
		//$this->mycache->set('testaaa',43445,300);
		//$aaa = $this->mycache->get('testaaa');
		//echo $aaa;
		//exit;
		$ret['code'] = 0;
		if($username==''){
			$ret['msg'] = '请输入用户名或邮箱';
			$ret['code'] = 1;
		}elseif ($password==''){
			$ret['msg'] = '请输入密码';
			$ret['code'] = 2;
		}else{
			$this->load->model('User_model', 'user');
			$tmpRow = $this->user->check_login_errnum( $this->input->get_post('username'));
			if($tmpRow && $tmpRow['error_num']>=5){
				$ret['msg'] = '密码输入错误过多，该账户已被锁定，请联系客服解锁或者明日再试';
				$ret['code'] = 3;
			}else{
				$user = $this->user->check_login($username,$password);
				if(isset($user['user_id'])){
					if($user['fstatus']==3){
						$ret['msg'] = '该账户已注销';
						$ret['code'] = 4;
					}elseif ($user['fstatus']==4){
						$ret['msg'] = '该账户已冻结';
						$ret['code'] = 5;
					}else{
						$ip = $this->js->get_ip();
						$now = time();
						$user['login_time'] = $now;
						//$this->session->set_userdata('ych_user',$user);
						
						$user = $this->user->get_by_uid($user['user_id']);
						$setArr = array(
							'logintime' => $user['logintime']+1,
							'uptime' => $user['lasttime'],
							'upip' => $user['lastip'],
							'lasttime' => $now,
							'error_num' => 0,
							'lastip' => $ip,
						);
						$this->user->update($setArr,array('user_id'=>$user['user_id']));
						
						//新增 添加登录日志
						$addLog = array(
							'login_name' => $username,
							'login_state' => 1,
							'login_time' => $now,
							'login_ip' => $ip
						);
						$this->user->add_user_login_log($addLog);
						
						$retUser = array(
							'user_id' => $user['user_id'],
							'username' => $user['username'],
							'email' => $user['email'],
							'realname' => $user['realname'],
							'phone' => $user['phone'],
							//'qq' => $user['qq'],
						);
						
						$token_time = time();
						$token_val = md5($user['user_id'].$user['username'].time());
						$token_key = 'token_'.$user['user_id'];
						$this->mycache->set($token_key,$token_val,3600*24);
						//$this->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
						//$this->cache->save($token_key, $token_val, 3600*24);
						$ret['msg'] = '登录成功';
						$ret['token'] = $token_val;
						$ret['user'] = $retUser;
						$ret['code'] = 0;
					}
				}else{
					$ret['msg'] = '账户或密码错误，请重试';
					$ret['code'] = 6;
				}
			}
		}
		echo json_encode($ret);
		
//		$ret['msg'] = "密码输入错误过多，该账户已被锁定，请联系客服解锁或者明日再试";
//		$this->load->view('mobile/msg',$ret);
	}
}